from flask import Blueprint, request, make_response
from flask_login import login_required

from apps.a_common.error import EmptyContent
from apps.a_common.response import success_response, error_response
from apps.foundation import log, cache
from utils.encode import uuid
from utils.storage import post_file_to_storage, get_file_from_storage, get_file_download_url

file_blueprint = Blueprint('files', __name__)


@file_blueprint.route('/files/images/<path:image_url>/', methods=['GET'])
@cache.memoize(timeout=3600)
def _get_image(image_url):
    """
    获得图片
    ---
    tags:
      - file
    parameters:
      - name: image_url
        in : path
        type: string
        required: false
        description: 图片的url
    """
    img_byte = get_file_from_storage(image_url)
    response = make_response(img_byte)
    response.headers['Content-Type'] = 'image/png'
    return response


@file_blueprint.route('/files/images/', methods=['POST'])
@login_required
def _post_image():
    """
    上传图片
    ---
    tags:
      - file
    parameters:
      - name: image
        in : formData
        type: file
        required: true
        description: 可以上传多张图片，key随意。一张图片和多张图片的返回格式有所不同
    """
    img_line = request.files

    if len(img_line) == 0:
        return error_response(EmptyContent())
    result_line = []
    for img in img_line.values():
        name = '{}.{}'.format(uuid(), img.filename.rsplit('.', 1)[-1])
        log.info('post image key name {}'.format(name))
        result_line.append(get_file_download_url(post_file_to_storage(name, img)))

    log.info('the last result line: {}'.format(result_line))
    if len(result_line) == 1:
        return success_response({'image_url': result_line[0]})
    return success_response({'image_url_line': result_line})
